//
//  BMHCashOutViewController.m
//  BMHVideoMain
//
//  Created by 陈宪栋 on 2017/7/10.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "BMHCashOutViewController.h"
#import <ReactiveCocoa.h>
#import <Masonry.h>
#import "UIImage+Gradient.h"
#import "BMHCashOutAuthorizeViewController.h"
#import "XLHTTPSessionManager+CashOut.h"
#import "XLWebViewController.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import <IQKeyboardManager.h>
#import "BMHWithdrawalRecordVController.h" //体现记录

@interface TextField : UITextField

@end

@implementation TextField
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    return NO;
}

- (void)deleteBackward {
    [super deleteBackward];
}
@end

@interface BMHCashOutViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) UIButton *actionButton;
@property (nonatomic, assign) BOOL isAuthorized;

@property (nonatomic, copy) NSString *amount;
@property (nonatomic, strong) NSString *openId;
@property (nonatomic, assign) NSInteger signStatus;

@property (nonatomic, strong) UILabel *walletBalanceLabel;
@property (nonatomic, strong) UILabel *monthTotalCashOutLabel;
@property (nonatomic, strong) UILabel *canCashOutLabel;
@property (nonatomic, strong) UILabel *taxLabel;
@property (nonatomic, strong) UILabel *actualMoneyLabel;
@property (nonatomic, strong) TextField *textField;
@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, copy) NSString *cashOutMoney;

@property (nonatomic, assign) double maxCashOutMoney;

@property (nonatomic, copy) NSString *monthCashOut;

@property (nonatomic, weak) RACDisposable *fetchTaxDisposable;

@property (nonatomic, assign) NSInteger tapCount;
@end

@implementation BMHCashOutViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"提现";
    [self setupView];
    //    [self setupData];
    [self bindData];
    [self refreshUserInfo];
    [self fetchData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[[XLHTTPSessionManager sharedManager] getContractStatusWithUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        // 0：未签约 1:申请 2:签约成功 3:签约失败
        NSInteger status = [[x objectForKey:@"status"] integerValue];
        self.signStatus = status;
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
    [self canCashOutData];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.shouldShowToolbarPlaceholder = NO;
    manager.enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.shouldShowToolbarPlaceholder = YES;
    manager.enableAutoToolbar = YES;
}

- (void)canCashOutData {
}

- (void)setupView {
    
    [self showBackButton:NULL];
    _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_rightButton setTitle:@"提现记录" forState:UIControlStateNormal];
    [_rightButton setTitleColor:HEXCOLOR(0x000000) forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(cashOutRecordAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 25)];
    backView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:backView];
    UIView *backView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 70, ScreenWidth, 25)];
    backView2.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:backView2];
    _walletBalanceLabel = [[UILabel alloc] init];
    _walletBalanceLabel.font = [UIFont systemFontOfSize:18];
    _walletBalanceLabel.textColor = HEXCOLOR(0xffbb01);
    [self.view addSubview:_walletBalanceLabel];
    [_walletBalanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(85);
        make.top.equalTo(self.view.mas_top).offset(35);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:18];
    label.textColor = HEXCOLOR(0x9395a2);
    label.text = @"账户余额";
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset (10);
        make.centerY.equalTo(_walletBalanceLabel);
    }];
    
    _monthTotalCashOutLabel = [[UILabel alloc] init];
    _monthTotalCashOutLabel.font = [UIFont systemFontOfSize:14];
    _monthTotalCashOutLabel.textColor = HEXCOLOR(0x9395a2);
    [self.view addSubview:_monthTotalCashOutLabel];
    [_monthTotalCashOutLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(84);
        make.left.equalTo(self.view.mas_left).offset(15);
    }];
    
    UIButton *recordButton = [[UIButton alloc] init];
    recordButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [recordButton setTitleColor:HEXCOLOR(0x9395a2) forState:UIControlStateNormal];
    [recordButton setTitle:@"提现记录" forState:UIControlStateNormal];
    [recordButton addTarget:self action:@selector(cashOutRecordAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:recordButton];
    [recordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_monthTotalCashOutLabel.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-15);
    }];
    recordButton.hidden = YES;
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_monthTotalCashOutLabel.mas_bottom).offset(10);
        make.left.and.right.equalTo(self.view);
        make.height.mas_equalTo(180);
    }];
    
    _canCashOutLabel = [[UILabel alloc] init];
    _canCashOutLabel.font = [UIFont systemFontOfSize:16];
    _canCashOutLabel.textColor = HEXCOLOR(0x000000);
    [contentView addSubview:_canCashOutLabel];
    [_canCashOutLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.mas_left).offset(15);
        make.top.equalTo(contentView.mas_top).offset(14);
    }];
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = [UIFont systemFontOfSize:12];
    tipLabel.textColor = HEXCOLOR(0x9395a2);
    tipLabel.text = @"单次提现额度:¥50~¥5000";
    [contentView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(contentView.mas_right).offset(-7);
        make.bottom.equalTo(_canCashOutLabel.mas_bottom);
    }];
    
    UILabel *YLabel = [[UILabel alloc] init];
    YLabel.font = [UIFont systemFontOfSize:24];
    YLabel.textColor = HEXCOLOR(0x000000);
    YLabel.text = @"¥";
    [contentView addSubview:YLabel];
    CGSize YSize = [YLabel sizeThatFits:CGSizeMake(30, 30)];
    [YLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.mas_left).offset(15);
        make.top.equalTo(_canCashOutLabel.mas_bottom).offset(27);
        make.size.mas_equalTo(YSize);
    }];
    UIButton *AllButton = [[UIButton alloc] init];
    [AllButton setTitle:@"全部" forState:UIControlStateNormal];
    AllButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [AllButton addTarget:self action:@selector(AllCashOut) forControlEvents:UIControlEventTouchUpInside];
    [AllButton setTitleColor:RGB_HEX(0x42C570) forState:UIControlStateNormal];
    [contentView addSubview:AllButton];
    [AllButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(contentView.mas_right).offset(-7);
        make.centerY.equalTo(YLabel);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];
    _textField = [[TextField alloc] init];
    _textField.font = [UIFont systemFontOfSize:18];
    _textField.textColor = HEXCOLOR(0x000000);
    _textField.tintColor = [UIColor darkGrayColor];
    _textField.delegate = self;
    _textField.keyboardType = UIKeyboardTypeDecimalPad;
    _textField.keyboardAppearance = UIKeyboardAppearanceLight;
    [contentView addSubview:_textField];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(YLabel.mas_right).offset(3);
        make.bottom.equalTo(YLabel.mas_bottom);
        make.top.equalTo(_canCashOutLabel.mas_bottom).offset(28);
        make.right.equalTo(contentView.mas_right).offset(-62);
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = HEXCOLOR(0x100f17);
    [contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(YLabel.mas_bottom).offset(27);
        make.left.equalTo(contentView.mas_left).offset(12);
        make.right.equalTo(contentView.mas_right).offset(-12);
        make.height.mas_equalTo(1.0 / [UIScreen mainScreen].scale);
    }];
    
    UILabel *taxLabel = [[UILabel alloc] init];
    taxLabel.font = [UIFont systemFontOfSize:14];
    taxLabel.textColor = HEXCOLOR(0x9395a2);
    taxLabel.text = @"应缴税额";
    [contentView addSubview:taxLabel];
    [taxLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.mas_left).offset(15);
        make.top.equalTo(line.mas_bottom).offset(22);
    }];
    
    _taxLabel = [[UILabel alloc] init];
    _taxLabel.font = [UIFont systemFontOfSize:14];
    _taxLabel.textColor = HEXCOLOR(0xffbb01);
    [contentView addSubview:_taxLabel];
    [_taxLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(taxLabel.mas_right).offset(5);
        make.top.equalTo(line.mas_bottom).offset(22);
    }];
    
    UILabel *actualMoneyLabel = [[UILabel alloc] init];
    actualMoneyLabel.font = [UIFont systemFontOfSize:14];
    actualMoneyLabel.textColor = HEXCOLOR(0x9395a2);
    actualMoneyLabel.text = @"实际到账";
    [contentView addSubview:actualMoneyLabel];
    [actualMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_taxLabel.mas_right).offset(20);
        make.top.equalTo(_taxLabel.mas_top);
    }];
    
    _actualMoneyLabel = [[UILabel alloc] init];
    _actualMoneyLabel.font = [UIFont systemFontOfSize:14];
    _actualMoneyLabel.textColor = HEXCOLOR(0xffbb01);
    [contentView addSubview:_actualMoneyLabel];
    [_actualMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(actualMoneyLabel.mas_right).offset(5);
        make.top.equalTo(_taxLabel.mas_top);
    }];
    
    UIButton *taxButton = [[UIButton alloc] init];
    taxButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [taxButton setTitleColor:HEXCOLOR(0x42C570) forState:UIControlStateNormal];
    [taxButton setTitle:@"扣税说明" forState:UIControlStateNormal];
    [taxButton addTarget:self action:@selector(taxIntroductionAction:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:taxButton];
    [taxButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(taxLabel.mas_centerY);
        make.right.equalTo(contentView.mas_right).offset(-15);
    }];
    
    _actionButton = [[UIButton alloc] init];
    _actionButton.layer.cornerRadius = 24;
    _actionButton.layer.masksToBounds = YES;
    _actionButton.enabled = NO;
    _actionButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_actionButton setBackgroundColor:RGB_HEX(0xFFBB01)];
    [_actionButton addTarget:self action:@selector(cashOutAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_actionButton];
    [_actionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contentView.mas_bottom).offset(22);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth - 30, 48));
    }];
}

- (void)setupData:(NSDictionary *)dic {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"TotalMoney"]];
    NSNumber *TotalMoney = [numberFormatter numberFromString:string];
    NSDecimalNumber *totalDec = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%lf", TotalMoney.doubleValue]];
    _walletBalanceLabel.text = F(@"¥%@", [dic objectForKey:@"TotalMoney"]);
    _textField.placeholder = [NSString stringWithFormat:@"最多可提现%@",_walletBalanceLabel.text];
    //    _monthTotalCashOutLabel.text = F(@"本月累计提现:%@元", self.monthCashOut ?: @"0");
    //    _canCashOutLabel.text = F(@"可提现%@元", totalDec.stringValue);
    _canCashOutLabel.text = @"提现金额";
    _taxLabel.text = @"0元";
    _actualMoneyLabel.text = @"0元";
    
    self.cashOutMoney = @"0";
    self.maxCashOutMoney = totalDec.doubleValue > 5000 ? 5000 : totalDec.doubleValue;
}

- (void)bindData {
    @weakify(self);
    [[self.textField.rac_textSignal skip:1] subscribeNext:^(NSString *text) {
        @strongify(self);
        //输入大于可提现金额则强制将输入金额改为可提现金额
        if (text.doubleValue > self.maxCashOutMoney && self.cashOutMoney.length - 1 < text.length) {
            self.textField.text = F(@"%.2lf", self.maxCashOutMoney);
        }
        //小数点后超过两位则截掉
        if ([text containsString:@"."] && text.length - [text rangeOfString:@"."].location > 3) {
            self.textField.text = [text substringWithRange:NSMakeRange(0, [text rangeOfString:@"."].location + 3)];
        }
        //最后一位为小数点的处理
        if ([text containsString:@"."] && [[text substringWithRange:NSMakeRange(text.length - 1, 1)] isEqualToString:@"."]) {
            self.cashOutMoney = F(@"0%@", [self.textField.text substringWithRange:NSMakeRange(0, self.textField.text.length - 1)]);
        } else {
            self.cashOutMoney = F(@"0%@", self.textField.text);
        }
        NSLog(@"%@", self.cashOutMoney);
    }];
    
    [[[RACObserve(self, cashOutMoney) distinctUntilChanged] skip:1] subscribeNext:^(NSString *cashOutMoney) {
        @strongify(self);
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fetchTax) object:nil];
        [self performSelector:@selector(fetchTax) withObject:nil afterDelay:1];
    }];
    
    [[RACObserve(self, signStatus) skip:1] subscribeNext:^(id x) {
        @strongify(self);
        if ([x integerValue] == 0) {
            [self.actionButton setTitle:@"尚未认证，点击认证" forState:UIControlStateNormal];
            self.actionButton.enabled = YES;
        } else if ([x integerValue] == 1) {
            [self.actionButton setTitle:@"认证处理中" forState:UIControlStateNormal];
            self.actionButton.enabled = NO;
        } else if ([x integerValue] == 2) {
            [self.actionButton setTitle:@"提现" forState:UIControlStateNormal];
            self.actionButton.enabled = YES;
        } else if ([x integerValue] == 3) {
            [self.actionButton setTitle:@"认证失败，重新认证" forState:UIControlStateNormal];
            self.actionButton.enabled = YES;
        } else {
            self.actionButton.enabled = NO;
        }
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [tap.rac_gestureSignal subscribeNext:^(id x) {
        @strongify(self);
        self.tapCount++;
    }];
    [self.navigationController.navigationBar addGestureRecognizer:tap];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [_walletBalanceLabel sizeToFit];
    [_monthTotalCashOutLabel sizeToFit];
    [_canCashOutLabel sizeToFit];
    [_taxLabel sizeToFit];
    [_actualMoneyLabel sizeToFit];
}

- (void)fetchTax {
    if (self.cashOutMoney.doubleValue == 0) {
        self.taxLabel.text = @"0元";
        self.actualMoneyLabel.text = @"0元";
        return;
    }
    [self.fetchTaxDisposable dispose];
    @weakify(self);
    self.fetchTaxDisposable = [[[XLHTTPSessionManager sharedManager] getWithholdingMoneyWithUserId:[[XLAccountManager shareInstance] model].Id money:self.cashOutMoney] subscribeNext:^(id x) {
        @strongify(self);
        NSNumber *amountDeducted = [x objectForKey:@"amountDeducted"];
        self.taxLabel.text = F(@"%@元", [x objectForKey:@"amountDeducted"]);
        NSDecimalNumber *amountDeductedDec = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%lf", amountDeducted.doubleValue]];
        NSDecimalNumber *cashOutMoneyDec = [NSDecimalNumber decimalNumberWithString:self.cashOutMoney];
        self.actualMoneyLabel.text = F(@"%@元", [cashOutMoneyDec decimalNumberBySubtracting:amountDeductedDec].stringValue);
    } error:^(NSError *error) {
        
    }];
}

- (void)fetchData {
    [[[XLHTTPSessionManager sharedManager] getMonthWithdrawDepositMoneyWithUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSDecimalNumber *actualarrivalDec = [NSDecimalNumber decimalNumberWithString:F(@"%@", x[@"actualarrival"])];
        NSDecimalNumber *amountDeductedDec = [NSDecimalNumber decimalNumberWithString:F(@"%@", x[@"amountDeducted"])];
        self.monthCashOut = [actualarrivalDec decimalNumberByAdding:amountDeductedDec].stringValue;
        //        _monthTotalCashOutLabel.text = F(@"本月累计提现:%@元", self.monthCashOut);
    } error:^(NSError *error) {
    }];
}

- (void)refreshData {
    
}

- (void)refreshUserInfo {
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/Balance/GetUserBalance" parameters:@{@"userId":[[XLAccountManager shareInstance]model].Id} resultClass:nil]subscribeNext:^(id x) {
        NSDictionary *dic = x;
        [self setupData:dic];
    } error:^(NSError *error) {
        
    }];
    //    [[[XLHTTPSessionManager sharedManager] getUserInfoWithUserId:[[XLAccountManager shareInstance] model].Id secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(XLUserInfoModel *model) {
    //        [UserDefaults setObject:model.Id forKey:UserID];
    //        [UserDefaults setObject:model.HeadImg forKey:UserHead];
    //        [UserDefaults setObject:model.NickName forKey:UserNick];
    //        model.SecretKey = [[XLAccountManager shareInstance] model].SecretKey;
    //        [[XLAccountManager shareInstance] updateUserInfo:model];
    //        [self setupData];
    //    } error:^(NSError *error) {
    //
    //    }];
}

- (void)cashOut {
    if (self.cashOutMoney.doubleValue < 50 && self.tapCount < 25) {
        [MBProgressHUD showContent:@"满50元可提现" toView:self.view];
        return;
    }
    [MBProgressHUD showMessage:@"" toView:self.view];
    [[[XLHTTPSessionManager sharedManager] cashOutWithUserId:[[XLAccountManager shareInstance] model].Id money:self.cashOutMoney] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:@"提现申请成功" toView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:error.userInfo[NSLocalizedDescriptionKey] toView:self.view];
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
        return NO;
    }
    return YES;
}

#pragma mark - action
- (void)cashOutAction:(UIButton *)button {
    if (_textField.isFirstResponder) {
        [_textField resignFirstResponder];
    }
    if (self.signStatus == 0 || self.signStatus == 3) {
        BMHCashOutAuthorizeViewController *vc = [[BMHCashOutAuthorizeViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [self cashOut];
    }
}
- (void)AllCashOut{
    self.textField.text = F(@"%.2lf", self.maxCashOutMoney);
    self.cashOutMoney = F(@"%.2lf", self.maxCashOutMoney);
}
//提现记录
- (void)cashOutRecordAction:(UIButton *)button {
    BMHWithdrawalRecordVController *withdrawalVC = [[BMHWithdrawalRecordVController alloc]init];
    [self.navigationController pushViewController:withdrawalVC animated:YES];
}

//扣税说明
- (void)taxIntroductionAction:(UIButton *)button {
    XLWebViewController *vc = [[XLWebViewController alloc] init];
    vc.url = @"http://xinliao.interface.baomihua.com/taxXinLiao.html";
    [self.navigationController pushViewController:vc animated:YES];
}


@end
